package com.ylbh.modules.goods.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ylbh.common.exception.NormalException;
import com.ylbh.common.pojo.goods.dto.*;
import com.ylbh.common.pojo.goods.vo.*;
import com.ylbh.common.utils.*;
import com.ylbh.modules.accessory.CombinedCommodities;
import com.ylbh.modules.accessory.GoodsInventoryDetails;
import com.ylbh.modules.accessory.GoodsInventoryDetailsToJsons;
import com.ylbh.modules.comment.mapper.CommentMapper;
import com.ylbh.modules.goods.mapper.GoodsSpecMapper;
import com.ylbh.modules.goods.mapper.ShoppingGoodsMapper;
import com.ylbh.modules.goods.service.GoodsSpecService;
import com.ylbh.modules.goods.service.ShoppingGoodsService;
import com.ylbh.modules.sys.service.SysRoleService;
import org.apache.commons.lang.StringEscapeUtils;
import org.apache.commons.lang.StringUtils;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.math.BigDecimal;
import java.net.URL;
import java.net.URLDecoder;
import java.text.DecimalFormat;
import java.util.*;


/**
 * @author mgh
 */
@Service
public class ShoppingGoodsServiceImpl extends ServiceImpl<ShoppingGoodsMapper, GoodsDTO> implements ShoppingGoodsService {

    private final Logger log = LoggerFactory.getLogger(ShoppingGoodsServiceImpl.class);

    @Autowired
    private ShoppingGoodsMapper shoppingGoodsMapper;
    @Autowired
    private GoodsSpecService goodsSpecService;
    @Autowired
    private SysRoleService sysRoleService;
    @Autowired
    private PictureRetrievalUtils pictureRetrievalUtils;
    @Autowired
    private CommentMapper commentMapper;

    @Value("${url.shoppingMainImage}")
    private String shoppingMainImage;

    @Value("${url.addEsGoods}")
    private String addEsGoods;

    @Value("${url.modifyEsGoods}")
    private String modifyEsGoods;

    @Value("${url.removeEsGoods}")
    private String removeEsGoods;

    @Autowired
    private GoodsSpecMapper goodsSpecMapper;

    @Autowired
    RedisUtils redisUtils;

    /**
     * 商品信息列表
     * @param goodsListDTO
     * @return
     */
    @Override
    public PageUtils queryGoodsList(GoodsListDTO goodsListDTO) {
        Page<Object> page = new Page<>(goodsListDTO.getPage(), goodsListDTO.getLimit());
        List<GoodsListVO> list = shoppingGoodsMapper.selectGoodsList(goodsListDTO, page);
        for (GoodsListVO vo : list) {
            String sku = vo.getGoodsInventoryDetail();
            if(StringUtils.isNotBlank(sku)){
                vo.setGoodsInventoryDetail(goodsSpecService.sortOutSku(sku));
            }
            if (!StringUtils.isEmpty(vo.getName()) && !StringUtils.isEmpty(vo.getPath())) {
                vo.setImg(shoppingMainImage + vo.getPath() + "/" + vo.getName());
            }

            if (null != vo.getId()) {
                vo.setUrl("http://www.yilianbaihui.cn/item_show.html?goodsId=" + vo.getId());
            }

        }
        Page<GoodsListVO> page1 = new Page<>();
        page1.setRecords(list).setTotal(page.getTotal());
        return new PageUtils(page1);
    }

    /**
     * 商品信息详情
     * @param id
     * @return
     */
    @Override
    public GoodsDetailsVO getGoodsById(Long id) {
        GoodsDetailsVO vo = shoppingGoodsMapper.selectGoodsById(id);
        if (null != vo) {
            if (!StringUtils.isEmpty(vo.getPath()) && !StringUtils.isEmpty(vo.getName())) {
                vo.setImg(shoppingMainImage + vo.getPath() + "/" + vo.getName());
            }
        }
            List<RotationChartVO> chart = shoppingGoodsMapper.rotationChart(vo.getId());
            for (RotationChartVO v : chart) {
                v.setUrl(shoppingMainImage + v.getUrl());
            }
            vo.setRotationChart(chart);

        String sku = vo.getGoodsInventoryDetail();
        vo.setGoodsInventoryDetail(goodsSpecService.sortOutSku(sku));

        // 去查询该商品是否是已经添加到活动的商品
        GoodsDetailsVO activity = shoppingGoodsMapper.selectIsActivityGoods(id);
        if (null != activity) {
            if (!StringUtils.isEmpty(activity.getActivityTitle()))
                vo.setActivityTitle(activity.getActivityTitle());
            vo.setIsActivityGoods(activity.getIsActivityGoods());
        }
        return vo;
    }

    /**
     * 修改商城商品信息详情
     * @param goodsDTO
     * @return
     */
    @Override
    public CommonResult<String> modifyGoodsById(GoodsDTO goodsDTO, Long userId) {
        // 查询出商品的原信息
        GoodsDetailsVO oldGoodsInfo = getGoodsById(goodsDTO.getId());
        // 删除检索图片的数据  因为我不知道修改商品的时候有没有改分类，有没有改类型，所以只能删了重新加入
        pictureRetrievalUtils.productDeleteByUrl(oldGoodsInfo);

        AccessoryDTO accessoryDTO = new AccessoryDTO();
        accessoryDTO.setAddTime(new Date());
        GoodsPictureVO intercepts ;
        Long mainImg = null;
        if (goodsDTO.getMainImg() != null && goodsDTO.getMainImg().size() > 0) {
            // 主图截取开始
            String url = goodsDTO.getMainImg().get(0).getUrl();

            url = filterTaoBaoImg(url);
            if(StringUtils.isBlank(url)){
                // 主图上传失败返回
                return Ref.error("主图上传失败，请重新选择图片");
            }
            // 设置图片全路径方便图片检索用
            goodsDTO.setMainImgUrl(url);

            intercepts = intercepts(url);
            accessoryDTO.setPath(intercepts.getPath());
            accessoryDTO.setId(goodsDTO.getMainImg().get(0).getId());
            accessoryDTO.setName(intercepts.getName());
            shoppingGoodsMapper.updateGoodPhoto(accessoryDTO);
            mainImg = accessoryDTO.getId();
            // 主图截取结束
        }
        if (goodsDTO.getRollingImg() != null && goodsDTO.getRollingImg().size() > 0) {
            // 轮播图截取开始
            for (GoodsImgDTO i : goodsDTO.getRollingImg()) {
                String url = i.getUrl();
                url = filterTaoBaoImg(url);
                if(StringUtils.isBlank(url)){
                    // 图上传失败返回
                    continue;
                }
                if (i.getId() != 0) {
                    intercepts = intercepts(url);
                    accessoryDTO.setPath(intercepts.getPath());
                    accessoryDTO.setId(i.getId());
                    accessoryDTO.setName(intercepts.getName());
                    shoppingGoodsMapper.updateGoodPhoto(accessoryDTO);
                } else {
                    intercepts = intercepts(url);
                    accessoryDTO.setPath(intercepts.getPath());
                    accessoryDTO.setName(intercepts.getName());
                    shoppingGoodsMapper.insertGoodPhoto(accessoryDTO);
                    shoppingGoodsMapper.insertRollingImg(goodsDTO.getId(), accessoryDTO.getId());
                }
            }
        }

            // 删除图片后，同时删除数据记录
        if (goodsDTO.getDeleteRollingImgId() != null && goodsDTO.getDeleteRollingImgId().length > 0) {
            for (Long i : goodsDTO.getDeleteRollingImgId()) {
                if (i != 0) {
                    // 删除中间表记录
                    shoppingGoodsMapper.deleteGoodsPhoto(i, goodsDTO.getId());
                    // 在图片表删除图片
                    shoppingGoodsMapper.deleteGoodsAcc(i);
                }
            }
        }

        if(goodsDTO.getCheckBoxChangeFlag() != null && goodsDTO.getCheckBoxChangeFlag() == 1){
            //删除商品规格
            shoppingGoodsMapper.deleteGoodsSpec(goodsDTO.getId());
            // 设置规格
            List<HashMap> hashMaps = JSONArray.parseArray(goodsDTO.getGoodsInventoryDetail(), HashMap.class);
            String id = hashMaps.stream()
                    .map(e -> e.get("id").toString())
                    .reduce("_", String::concat);
            String[] idArray= id.split("_");
            // 去重规格属性
            HashSet<String> idSet = new HashSet<String>(Arrays.asList(idArray));
            for (String s : idSet) {
                if(StringUtils.isNotBlank(s)){
                    shoppingGoodsMapper.insertGoodsSpec(s,goodsDTO.getId());
                }
            }
        }

        // 过滤商品详情
//        filterGoodsDetails(goodsDTO);

        // 如果商品是多规格的，就让该商品中价格最低的显示在商品的标签上
        List<GoodsInventoryDetailsToJson> toJsonList = FastJsonUtil.toList(goodsDTO.getGoodsInventoryDetail(), GoodsInventoryDetailsToJson.class);
        // 如果商品只有一个规格
        if (toJsonList.size() > 0 && toJsonList.size() == 1) {
            if ("1".equals(toJsonList.get(0).getPriceType())) {
                goodsDTO.setVipPrice(new BigDecimal("0"));
            } else if ("2".equals(toJsonList.get(0).getPriceType())) {
                goodsDTO.setVipPrice(new BigDecimal(toJsonList.get(0).getVipPrice()));
            }
            goodsDTO.setGoodsPrice(new BigDecimal(toJsonList.get(0).getPrice()));
            goodsDTO.setIntegral(Integer.parseInt(toJsonList.get(0).getIntegral()));
            goodsDTO.setGoodsCostingPrice(new BigDecimal(toJsonList.get(0).getGoodsCostingPrice()));
        }
        // 如果商品有多个规格
        if (toJsonList.size() > 1) {
            String s = null;
            int index = 0;
            for (int i = 0; i < toJsonList.size(); i++) {
                if ("1".equals(goodsDTO.getPriceType())) {
                   if (null == s) {
                       s = toJsonList.get(i).getIntegral();
                       index = i;
                   } else {
                       if (Integer.parseInt(s) > Integer.parseInt(toJsonList.get(i).getIntegral())) {
                           s = toJsonList.get(i).getIntegral();
                           index = i;
                       }
                   }
                } else if ("2".equals(goodsDTO.getPriceType())) {
                    if (null == s) {
                        s = toJsonList.get(i).getVipPrice();
                        index = i;
                    } else {
                        if (new BigDecimal(s).compareTo(new BigDecimal(toJsonList.get(i).getVipPrice())) > -1) {
                            s = toJsonList.get(i).getVipPrice();
                            index = i;
                        }
                    }
                }
            }
            if ("1".equals(goodsDTO.getPriceType())) {
                goodsDTO.setVipPrice(new BigDecimal("0"));
            }else if ("2".equals(goodsDTO.getPriceType())) {
                goodsDTO.setVipPrice(new BigDecimal(toJsonList.get(index).getVipPrice()));
            }
            goodsDTO.setGoodsPrice(new BigDecimal(toJsonList.get(index).getPrice()));
            goodsDTO.setIntegral(Integer.parseInt(toJsonList.get(index).getIntegral()));
            goodsDTO.setGoodsCostingPrice(new BigDecimal(toJsonList.get(index).getGoodsCostingPrice()));
        }

        if (null != goodsDTO.getGoodsDetails() && !StringUtils.isEmpty(goodsDTO.getGoodsDetails())) {
            goodsDTO.setGoodsDetails(goodsDTO.getGoodsDetails().replace("https://assets.alicdn.com/kissy/1.0.0/build/imglazyload/spaceball.gif", ""));
            String template = "<style type=\\\"text/css\\\">*,:after,:before{box-sizing:border-box;margin:0;padding:0;word-wrap:break-word}.dc{padding-bottom:2.5rem;}p{color:#54565e;font-weight:300;font-size:14px;font-family:PingFangSC;line-height:25px}img{display:block;width:100%}video{width:100%;height:200px;}</style>";
            goodsDTO.setGoodsDetails(StringEscapeUtils.unescapeJava(template) + goodsDTO.getGoodsDetails());
        }
        shoppingGoodsMapper.updateById(goodsDTO);

        // 将图片加入百度图片搜索服务器
//        if(StringUtils.isNotBlank(goodsDTO.getMainImgUrl())){
//            //添加商品图片检索
//            pictureRetrievalUtils.productAddUrl(goodsDTO);
//        }

//        EsGoodsDTO esGoodsDTO = new EsGoodsDTO();
//        BeanUtils.copyProperties(goodsDTO, esGoodsDTO);
//        esGoodsDTO.setVipprice(goodsDTO.getVipPrice());
//        esGoodsDTO.setGoodsMainPhotoId(mainImg);
//        if(!StringUtils.isEmpty(esGoodsDTO.getGoodsName())) {
//            String goodsName = esGoodsDTO.getGoodsName().replace("&", "%26");
//            esGoodsDTO.setGoodsName(goodsName);
//        }
//        if(!StringUtils.isEmpty(esGoodsDTO.getGoodsBrief())) {
//            String goodsBrief = esGoodsDTO.getGoodsBrief().replace("&", "%26");
//            esGoodsDTO.setGoodsBrief(goodsBrief);
//        }
//        if(!StringUtils.isEmpty(esGoodsDTO.getSeoDescription())) {
//            String seoDescription = esGoodsDTO.getSeoDescription().replace("&", "%26");
//            esGoodsDTO.setSeoDescription(seoDescription);
//        }
//        if(!StringUtils.isEmpty(esGoodsDTO.getSeoKeywords())) {
//            String seoKeywords = esGoodsDTO.getSeoKeywords().replace("&", "%26");
//            esGoodsDTO.setSeoKeywords(seoKeywords);
//        }
//        String s = FastJsonUtil.toJSONString(esGoodsDTO);
//        HashMap<String, String> map = new HashMap<>();
//        map.put("data", s);
//        String httpPost = HttpClientHelperUtils.sendHttpPost(modifyEsGoods, map);
//        String httpURL = modifyEsGoods;
        goodsDTO.setGoodsMainPhotoId(mainImg);
        // 查询这个用户所属的角色是否是供应商
        Integer roleType = null;
        if (null != userId)
            roleType =  sysRoleService.selectRole(userId);
        else
            roleType = 1;
//        if (null != roleType && roleType != 6)
//            addEsGoodsHttp(modifyEsGoods, goodsDTO);
        if (null != roleType && roleType != 6) {
            HashMap<String, Object> map = new HashMap<>();
            map.put("id", goodsDTO.getId());
            String msg = HttpClientHelperUtils.sendHttpPostEs(modifyEsGoods, map);
            log.info("修改商品es返回信息：" + msg);

        }
//        String esGoods = getEsGoods(modifyEsGoods, goodsDTO);
//        log.info("=========================修改商品同时修改es服务器中的商品返回信息:" + esGoods);
        redisUtils.delete("seckillGoods" + goodsDTO.getId());
        return Ref.ok("修改成功");
    }


    private void filterGoodsDetails(GoodsDTO goodsDTO) {
        if (!StringUtils.isEmpty(goodsDTO.getGoodsDetails())) {
            // 过滤图片
            Document parse = Jsoup.parse(goodsDTO.getGoodsDetails());
            Elements imgs = parse.getElementsByTag("img");
            for (Element img :imgs) {
                String src = img.attr("src");
                if (!src.contains("image.yilianbaihui.cn")){
//                    String url = TaoBaoUtils.uploadFile(src, "https://www.taobao.com/", "consumer/upload/store/33307/");
                    String url = TaoBaoUtils.uploadFileGoods(src, "", "upload/store/33307");
                    if(StringUtils.isBlank(url)){
                        img.remove();
                    }else {
//                        img.attr("src",url);
                        img.attr("src", shoppingMainImage + url);
                    }
                }
            }
            goodsDTO.setGoodsDetails(parse.body().children().toString());
            String url = UploadHtmlFile.uploadHtmlOss2(goodsDTO.getGoodsDetails(), "goosdetails");
            goodsDTO.setNewDetailsUrl("https://file.yilianbaihui.cn/goosdetails/" + url);
        }
    }

    /**
     * 商城批量修改
     * @param type
     * @param ids
     */
    @Override
    public void batchModifyState(String type, Integer[] ids) {
        GoodsListDTO goodsListDTO = new GoodsListDTO();
        switch (type) {
            case "batchNew":
                goodsListDTO.setIsNew(1);
                break;
            case "batchCancelNew":
                goodsListDTO.setIsNew(0);
                break;
            case "batchBest":
                goodsListDTO.setIsBest(1);
                break;
            case "batchCancelBest":
                goodsListDTO.setIsBest(0);
                break;
            case "batchLowShelf":
                goodsListDTO.setGoodsStatuses(-1);
                break;
            case "batchUpShelf":
                goodsListDTO.setGoodsStatuses(0);
                break;
            case "batchDelete":
                goodsListDTO.setDeleteStatus(1);
            default:
                break;
        }

        if("batchDelete".equals(type)){
            for (Integer id:ids){
                // 查询出商品的原信息
                GoodsDetailsVO oldGoodsInfo = getGoodsById(id.longValue());
                // 删除图片检索
                pictureRetrievalUtils.productDeleteByUrl(oldGoodsInfo);
            }
        }
        shoppingGoodsMapper.batchUpdateState(goodsListDTO,ids);
        // 如果商品是下架，则要去删除es服务器中的信息
        if ("batchLowShelf".equals(type) || "batchDelete".equals(type)) {
            for (Integer id:ids) {
                HashMap<String, String> map = new HashMap<>();
                map.put("goodsId", id + "");
                String httpPost = HttpUtils.sendGet(removeEsGoods, map);
                log.info("=============================下架商品同时删除es商品信息：" + httpPost);
            }
        }

        // 如果商品是上架，那么要将商品添加到es
        if ("batchUpShelf".equals(type)) {
            for (Integer id:ids) {
//                GoodsDetailsVO goodsById = getGoodsById(id.longValue());
//                EsGoodsDTO esGoodsDTO = new EsGoodsDTO();
//                BeanUtils.copyProperties(goodsById, esGoodsDTO);
//                esGoodsDTO.setVipprice(goodsById.getVipPrice());
//                if(!StringUtils.isEmpty(esGoodsDTO.getGoodsName())) {
//                    String goodsName = esGoodsDTO.getGoodsName().replace("&", "%26");
//                    esGoodsDTO.setGoodsName(goodsName);
//                }
//                if(!StringUtils.isEmpty(esGoodsDTO.getGoodsBrief())) {
//                    String goodsBrief = esGoodsDTO.getGoodsBrief().replace("&", "%26");
//                    esGoodsDTO.setGoodsBrief(goodsBrief);
//                }
//                if(!StringUtils.isEmpty(esGoodsDTO.getSeoDescription())) {
//                    String seoDescription = esGoodsDTO.getSeoDescription().replace("&", "%26");
//                    esGoodsDTO.setSeoDescription(seoDescription);
//                }
//                if(!StringUtils.isEmpty(esGoodsDTO.getSeoKeywords())) {
//                    String seoKeywords = esGoodsDTO.getSeoKeywords().replace("&", "%26");
//                    esGoodsDTO.setSeoKeywords(seoKeywords);
//                }
//                String s = FastJsonUtil.toJSONString(esGoodsDTO);
                HashMap<String, String> map = new HashMap<>();
//                map.put("data", s);
                map.put("id",id.toString());
                String httpPost = HttpClientHelperUtils.sendHttpPost(addEsGoods, map);
                log.info("=========================上架商品添加到es服务器返回信息:" + httpPost);
            }
        }
    }

    /**
     * 修改商城商品sku信息详情
     * @param updateGoodsDetailsDTO
     */
    @Override
    public void modifySkuById(GoodsDetailsDTO updateGoodsDetailsDTO) {
        shoppingGoodsMapper.updateSkuById(updateGoodsDetailsDTO.getId(),updateGoodsDetailsDTO.getGoodsInventoryDetail());
    }

    private GoodsPictureVO intercepts(String url){
        GoodsPictureVO pictureDTO = new GoodsPictureVO();
        String path = url.substring(url.lastIndexOf("consumer") + 9, url.lastIndexOf("/"));
        String name = url.substring(url.lastIndexOf("/") + 1);
        pictureDTO.setPath(path);
        pictureDTO.setName(name);
        pictureDTO.setExt(name.substring(name.lastIndexOf(".") + 1));
        pictureDTO.setDate(new Date());
        return pictureDTO;
    }


    /**
     * 保存商品信息
     * @param goodsDTO
     * @return
     */
    @Override
    public CommonResult add(GoodsDTO goodsDTO, Long userId){
        Date date = new Date();
        goodsDTO.setAddTime(date);
        goodsDTO.setDeleteStatus(0);
        goodsDTO.setIsNew(1);
        goodsDTO.setSeoKeywords(goodsDTO.getGoodsName());
        goodsDTO.setGoodsBrief(goodsDTO.getGoodsName());
        // 查询这个用户所属的角色是否是供应商
        Integer roleType =  sysRoleService.selectRole(userId);
        if (null != roleType && roleType == 6) {
            goodsDTO.setGoodsManagerId(userId.intValue());
            goodsDTO.setGoodsStatus(1);
        } else {
            goodsDTO.setGoodsManagerId(33307);
            goodsDTO.setGoodsStatus(0);
        }
        goodsDTO.setGoodsStoreId(110);
        goodsDTO.setInventoryType("spec");
        goodsDTO.setGoodsCurrentPrice(goodsDTO.getVipPrice());
        goodsDTO.setStorePrice(goodsDTO.getVipPrice());
        goodsDTO.setIsBest(0);

        // 保存主图
        AccessoryDTO accessoryDTO = new AccessoryDTO();
        accessoryDTO.setAddTime(date);
//        Long mainImg = null;
        if (goodsDTO.getMainImg().size() > 0) {
            // 主图截取开始
            String url = goodsDTO.getMainImg().get(0).getUrl();
//            url = filterTaoBaoImg(url);
//            if(StringUtils.isBlank(url)){
//                // 主图上传失败返回
//                return Ref.error("主图上传失败，请重新选择图片");
//            }
//            // 设置图片全路径方便图片检索用
//            goodsDTO.setMainImgUrl(url);

            GoodsPictureVO intercepts = intercepts(url);
            accessoryDTO.setPath(intercepts.getPath());
            accessoryDTO.setName(intercepts.getName());
            shoppingGoodsMapper.insertGoodPhoto(accessoryDTO);
//            mainImg = accessoryDTO.getId();
            // 主图截取结束
        }
        goodsDTO.setGoodsMainPhotoId(accessoryDTO.getId());
        if (!StringUtils.isEmpty(goodsDTO.getGoodsDetails())) {
            goodsDTO.setGoodsDetails(goodsDTO.getGoodsDetails().replace("https://du.hupucdn.com/FlyWbf5CVPLRropEWYbVH12kUGWs?imageView2/2/w/960", "https://image.yilianbaihui.cn/consumer/upload/security.jpg"));
            goodsDTO.setGoodsDetails(goodsDTO.getGoodsDetails().replace("https://du.hupucdn.com/news_byte52287byte_5b6f8390e75ad455639e5f376665fcd7_w1125h231.png?imageView2/2/w/960", "https://image.yilianbaihui.cn/consumer/upload/after.png"));
        }
        // 过滤商品详情
        filterGoodsDetails(goodsDTO);

        if (!StringUtils.isEmpty(goodsDTO.getGoodsDetails())) {
            goodsDTO.setGoodsDetails(goodsDTO.getGoodsDetails().replace("https://assets.alicdn.com/kissy/1.0.0/build/imglazyload/spaceball.gif", ""));
        }
        String template = "<style type=\\\"text/css\\\">*,:after,:before{box-sizing:border-box;margin:0;padding:0;word-wrap:break-word}.dc{padding-bottom:2.5rem;}p{color:#54565e;font-weight:300;font-size:14px;font-family:PingFangSC;line-height:25px}img{display:block;width:100%}video{width:100%;height:200px;}</style>";

        goodsDTO.setGoodsDetails(StringEscapeUtils.unescapeJava(template) + goodsDTO.getGoodsDetails());
        this.save(goodsDTO);
        // 商品的id
//        Long goodsId = goodsDTO.getId();

//        shoppingGoodsMapper.insertGoods(goodsDTO);
        log.info("添加的商品" + goodsDTO.getGoodsName() + "规格为：", goodsDTO.getGoodsInventoryDetail());
        List<HashMap> hashMaps = JSONArray.parseArray(goodsDTO.getGoodsInventoryDetail(), HashMap.class);
        String id = hashMaps.stream()
                .map(e -> e.get("id").toString())
                .reduce("_", String::concat);
        String[] idArray= id.split("_");
        // 去重规格属性
        HashSet<String> idSet = new HashSet<String>(Arrays.asList(idArray));
        for (String s : idSet) {
            if(StringUtils.isNotBlank(s)){
                shoppingGoodsMapper.insertGoodsSpec(s,goodsDTO.getId());
            }
        }

        for (GoodsImgDTO img : goodsDTO.getRollingImg()) {
            String url = img.getUrl();

            url = filterTaoBaoImg(url);
            if(StringUtils.isBlank(url)){
                // 图上传失败返回
                continue;
            }
            GoodsPictureVO intercepts = intercepts(url);
            accessoryDTO.setPath(intercepts.getPath());
            accessoryDTO.setName(intercepts.getName());
            shoppingGoodsMapper.insertGoodPhoto(accessoryDTO);
            shoppingGoodsMapper.insertRollingImg(goodsDTO.getId(), accessoryDTO.getId());
        }

        // 将图片加入百度图片搜索服务器
//        if(StringUtils.isNotBlank(goodsDTO.getMainImgUrl())){
//            //添加商品图片检索
//            pictureRetrievalUtils.productAddUrl(goodsDTO);
//        }

//        EsGoodsDTO esGoodsDTO = new EsGoodsDTO();
//        BeanUtils.copyProperties(goodsDTO, esGoodsDTO);
//        esGoodsDTO.setVipprice(goodsDTO.getVipPrice());
//        esGoodsDTO.setGoodsMainPhotoId(mainImg);
//        if(!StringUtils.isEmpty(esGoodsDTO.getGoodsName())) {
//            String goodsName = esGoodsDTO.getGoodsName().replace("&", "%26");
//            esGoodsDTO.setGoodsName(goodsName);
//        }
//        if(!StringUtils.isEmpty(esGoodsDTO.getGoodsBrief())) {
//            String goodsBrief = esGoodsDTO.getGoodsBrief().replace("&", "%26");
//            esGoodsDTO.setGoodsBrief(goodsBrief);
//        }
//        if(!StringUtils.isEmpty(esGoodsDTO.getSeoDescription())) {
//            String seoDescription = esGoodsDTO.getSeoDescription().replace("&", "%26");
//            esGoodsDTO.setSeoDescription(seoDescription);
//        }
//        if(!StringUtils.isEmpty(esGoodsDTO.getSeoKeywords())) {
//            String seoKeywords = esGoodsDTO.getSeoKeywords().replace("&", "%26");
//            esGoodsDTO.setSeoKeywords(seoKeywords);
//        }
//        String s = FastJsonUtil.toJSONString(esGoodsDTO);
//        HashMap<String, String> map = new HashMap<>();
//        map.put("data", s);
//        String httpPost = HttpClientHelperUtils.sendHttpPost(addEsGoods, map);

//        String httpURL = addEsGoods;
//        goodsDTO.setId(goodsId);
//        goodsDTO.setGoodsMainPhotoId(mainImg);
//        String esGoods = getEsGoods(addEsGoods, goodsDTO);
//        if (roleType != 6)
//            addEsGoodsHttp(addEsGoods, goodsDTO);
//
        if (null != roleType && roleType != 6) {
            HashMap<String, Object> map = new HashMap<>();
            map.put("id", goodsDTO.getId());
            String msg = HttpClientHelperUtils.sendHttpPostEs(addEsGoods, map);
            log.info("上传商品添加ES返回集：" + msg);
        }

//        log.info("=========================上传商品添加到es服务器返回信息:" + esGoods);
        return Ref.ok();
    }

    private String filterTaoBaoImg(String url){
        if (!url.contains("image.yilianbaihui.cn")){
            // 不包含说明是淘宝上传的商品
            return  TaoBaoUtils.uploadFile(url,"https://www.taobao.com/","consumer/upload/store/33307/");
        }
        return url;
    }
    /**
     * 商城商品导出
     * @param response
     * @param request
     */
    @Override
    public void goodsExcel(HttpServletResponse response, HttpServletRequest request) throws NormalException {
        GoodsListDTO dto = new GoodsListDTO();
        String priceType = request.getParameter("priceType");
        if (null != request.getParameter("goodsStatuses") && !"".equals(request.getParameter("goodsStatuses"))) {
            String goodsStatuses = request.getParameter("goodsStatuses");
            dto.setGoodsStatuses(Integer.parseInt(goodsStatuses));
        }
        String startTime = request.getParameter("startTime");
        String endTime = request.getParameter("endTime");
        String bestOrNew = request.getParameter("bestOrNew");
        String goodsManagerId = request.getParameter("goodsManagerId");
        dto.setPriceType(priceType);
//        dto.setStartTime(startTime);
//        dto.setEndTime(endTime);
        if(StringUtils.isNotBlank(startTime)){
            dto.setStartTime(startTime);
        }
        if(StringUtils.isNotBlank(endTime)){
            dto.setEndTime(startTime);
        }

        if(StringUtils.isNotBlank(bestOrNew)){
            dto.setBestOrNew(Integer.parseInt(bestOrNew));
        }
        if(StringUtils.isNotBlank(goodsManagerId)){
            dto.setGoodsManagerId(Integer.parseInt(goodsManagerId));
        }
        //GoodsExcelVO
        List<GoodsExcelEntityVO> goodsExcelEntityVO = shoppingGoodsMapper.selectGoodsExcel(dto);
        for (GoodsExcelEntityVO vo : goodsExcelEntityVO) {
            if (null != vo.getGoodsInventoryDetail()) {
                List<SpecificationsVO> List = JSON.parseArray(vo.getGoodsInventoryDetail(), SpecificationsVO.class);
                for (SpecificationsVO vo1 : List) {
                    StringBuffer sb = new StringBuffer("");
                    if (StringUtils.isNotBlank(vo1.getId())) {
                        List<SpecsDTO> dtos = goodsSpecMapper.selectSpecsById(vo1.getId().split(","));
                        for (SpecsDTO dto1 : dtos) {
                            if (null != dto1.getParName()) {
                                sb.append(dto1.getParName() + "/");
                            }
                        }
                    }
                    String str = new String(sb);
                    if (StringUtils.isNotBlank(str)) {
                        vo1.setName(str.substring(0,str.length() - 1));
                    }
                }
            }
        }
        //System.out.println(GoodsExcelVO.class);
        ExcelUtils.exportExcel(goodsExcelEntityVO, "商城商品","", GoodsExcelEntityVO.class,System.currentTimeMillis() + ".xls", response);
        //ExcelUtils.exportExcel(goodsExcelEntityVO, "商城商品","",GoodsExcelVO.class, System.currentTimeMillis() + ".xls", response);
    }

    @Override
    public void modifyIsNewByAddTime() {
        Date date =  DateUtils.todayWholePoint(new Date());
        Date statTime = DateUtils.addDateDays(date, -10);

        Date endTime= DateUtils.addDateDays(date, -9);
        shoppingGoodsMapper.updateIsNewByAddTime(0,statTime,endTime);
    }

    @Override
    public void modifyPriceType() {
//        List<GoodsDTO> dto = shoppingGoodsMapper.selectPriceType();
//        int st = 0;
//        for (GoodsDTO goodsDTO:dto) {
//            if ("1".equals(goodsDTO.getPriceType())) {
//                if (null != goodsDTO.getIsOnSale() && goodsDTO.getIsOnSale() == 1) {
//                    int i = goodsDTO.getIntegral() + goodsDTO.getExpressTransFee().multiply(new BigDecimal("5")).intValue();
//                    double v = new BigDecimal(goodsDTO.getIntegral()).divide(new BigDecimal(i), 3, BigDecimal.ROUND_HALF_UP).doubleValue();
//                    goodsDTO.setCombinPrice(new BigDecimal(v).multiply(new BigDecimal(10)).setScale(1, BigDecimal.ROUND_HALF_UP));
//                    st ++ ;
//                }
//                if (!StringUtils.isEmpty(goodsDTO.getGoodsInventoryDetail())) {
//                    List<GoodsInventoryDetailsToJson> toList = FastJsonUtil.toList(goodsDTO.getGoodsInventoryDetail(), GoodsInventoryDetailsToJson.class);
//                    Integer minIntegral = 0;
//                    for (int i = 0; i < toList.size(); i++) {
//                        GoodsInventoryDetailsToJson details = toList.get(i);
//                        details.setIntegral((goodsDTO.getExpressTransFee().multiply(new BigDecimal("5"))).intValue() + details.getIntegral());
//                        if (minIntegral == 0 && details.getIntegral() > 0) {
//                            minIntegral = details.getIntegral();
//                        }
//                        if (minIntegral > 0 && minIntegral > details.getIntegral()) {
//                            minIntegral = details.getIntegral();
//                        }
//                        details.setShowCostingPrice("0");
//                    }
//                    String toJSONString = FastJsonUtil.toJSONString(toList);
//                    goodsDTO.setGoodsInventoryDetail(toJSONString);
//                    goodsDTO.setIntegral(minIntegral);
//                }
//                goodsDTO.setExpressTransFee(new BigDecimal("0.1"));
//                System.out.println("执行商品信息："+ goodsDTO.toString());
//                shoppingGoodsMapper.updateById(goodsDTO);
//            }
//        }
//        System.out.println(st);
    }

    /**
     * 查询所有商品的图片地址
     * @return
     */
    @Override
    public List<GoodsQueryVO> queryGoodsImages() {
        List<GoodsQueryVO> goodsQueryVOList = shoppingGoodsMapper.selectGoodsQuery();
        for (GoodsQueryVO vo : goodsQueryVOList) {
            ArrayList<String> list = new ArrayList<>();
            list.add(vo.getGoodsMainImage());
            if (null != vo && !StringUtils.isEmpty(vo.getGoodsInventoryDetail())) {
                log.info("======================商品信息：" + vo.getId() + "=========================");
                // 将规格信息转化成对象
                List<GoodsInventoryDetailsToJson> toList = FastJsonUtil.toList(vo.getGoodsInventoryDetail(), GoodsInventoryDetailsToJson.class);
                for (GoodsInventoryDetailsToJson json : toList) {
                    if (!StringUtils.isEmpty(json.getImgPath())) {
                        list.add(json.getImgPath());
                    }
                }
            }
            // 去附件表中查询出轮播图的图片信息
            List<String> img = shoppingGoodsMapper.selectWheelPlantingImage(vo.getId());
            list.addAll(img);
            vo.setGoodsImages(list);
        }
        return goodsQueryVOList;
    }

    /**
     * 在列表查看对应sku查询是否已经是活动商品
     * @param id
     * @return
     */
    @Override
    public GoodsDetailsVO getIsActivityGoodsById(Long id) {
        return shoppingGoodsMapper.selectIsActivityGoods(id);
    }

    @Override
    public List<String> getGoodsCount() {
        List<GoodsDTO> list = shoppingGoodsMapper.selectGoodsCount();
        int fl = 0;
        int dh = 0;
        StringBuffer sb = new StringBuffer();
        ArrayList<String> list1 = new ArrayList<>();
        for (int i = 0; i < list.size(); i++) {
            GoodsDTO goodsDTO = list.get(i);
            List<GoodsInventoryDetailsToJson> toJsonList = FastJsonUtil.toList(goodsDTO.getGoodsInventoryDetail(), GoodsInventoryDetailsToJson.class);
//            if (null != toJsonList && toJsonList.size() >= 2 && goodsDTO.getPriceType().equals("1")) {
//                dh = dh + 1;
//            }
//            if (null != toJsonList && toJsonList.size() >= 2 && goodsDTO.getPriceType().equals("2")) {
//                fl = fl + 1;
//            }
            if (toJsonList.size() > 0) {
                if ("".equals(toJsonList.get(0).getId())) {
                    fl = fl + 1;
                    list1.add(list.get(i).getId().toString());
                    sb.append(list.get(i).getId() + ",");
                    HashMap<String, String> map = new HashMap<>();
                    map.put("goodsId", list.get(i).getId().toString());
                    String httpPost = HttpClientHelperUtils.sendHttpGet(removeEsGoods, map);
                    shoppingGoodsMapper.updateGoodsStatus(list.get(i).getId());
                    System.out.println(httpPost);
                }
            }
        }
        System.out.println(sb.toString());
        System.out.println("福利:" + fl);
        System.out.println("兑换:" + dh);
        return list1;
    }

    /**
     * 商城合并，查询商品
     * @return
     */
    @Override
    public List<GoodsDTO> getAllGoods() {
        return shoppingGoodsMapper.selectAllGoods();
    }

    /**
     * 商城合并，查询规格属性名
     * @param ids
     * @return
     */
    @Override
    public List<String> getSpecValueById(List<String> ids) {
        return shoppingGoodsMapper.selectSpecValueById(ids);
    }

    /**
     * 批量修改合并后的商品
     * @param list
     */
    @Override
    public void modifyMergeGoodsById(CombinedCommodities list) {
        shoppingGoodsMapper.updateMergeGoodsById(list);
    }

    /**
     * 查看对应商品评论
     * @param pageDTO
     * @return
     */
    @Override
    public PageUtils getGoodsCommentById(PageDTO pageDTO) {
        Page<Integer> page = new Page<>(pageDTO.getPage(), pageDTO.getLimit());
        List<ShoppingGoodsCommentVO> list = commentMapper.selectGoodsCommentById(pageDTO.getKeywords(), page);
        return new PageUtils(new Page<ShoppingGoodsCommentVO>().setTotal(page.getTotal()).setRecords(list));
    }

    @Override
    public Integer getCountByBrandId(String id) {
        return shoppingGoodsMapper.selectCountByBrandId(id);
    }

    /**
     * 删除商品评论
     * @param ids
     */
    @Override
    public void removeGoodsCommentByIds(List<String> ids) {
        commentMapper.updateGoodsCommentByIds(ids);
    }

    /**
     * 查询该商品是否添加过
     * @param sku
     * @return
     */
    @Override
    public int selectSku(String sku) {
        return shoppingGoodsMapper.selectSKu(sku);
    }

    /**
     * 计算商品的利润
     */
    @Override
    public void modifyGoodsCostingPrice() {
        // 查询出所有未删除的商品
        List<GoodsDTO> dto = shoppingGoodsMapper.selectIsDeleteGoods();
        for (GoodsDTO gd:dto) {
            if (!StringUtils.isEmpty(gd.getGoodsInventoryDetail())) {
                List<GoodsInventoryDetails> jsonToList = FastJsonUtil.toList(gd.getGoodsInventoryDetail(), GoodsInventoryDetails.class);
                for (GoodsInventoryDetails gid:jsonToList) {
//                    if (null == gid.getGoodsCostingPrice() || "0".equals(gid.getGoodsCostingPrice())) {
//                        System.out.println("id商品："+ gd.getId());
//                    }
                    if (!"0.00".equals(gid.getGoodsCostingPrice()) && !"0".equals(gid.getGoodsCostingPrice())) {
                        gid.setShowCostingPrice(new DecimalFormat("0.00").format(new BigDecimal(gid.getGoodsCostingPrice()).multiply(new BigDecimal("0.7"))));
                    }
                    if (null == gd.getGoodsCostingPrice()) {
                        gd.setGoodsCostingPrice(new BigDecimal(gid.getGoodsCostingPrice()));
                    } else {
                        if (gd.getGoodsCostingPrice().compareTo(new BigDecimal(gid.getGoodsCostingPrice())) == 1) {
                            gd.setGoodsCostingPrice(new BigDecimal(gid.getGoodsCostingPrice()));
                        }
                    }
                }
                gd.setGoodsInventoryDetail(JSON.toJSONString(jsonToList));
            }
            // 修改商品的利润
            shoppingGoodsMapper.updateGoodsCostPrice(gd);
        }
    }


    /**
     * 解析数据
     * @param dto
     */
    @Override
    public GoodsDetailsVO analyticalData(PoiZonGoodsDTO dto) {
        GoodsDetailsVO vo = new GoodsDetailsVO();
        if (!StringUtils.isEmpty(dto.getImages())) {
            String[] img = dto.getImages().split(",");
            List<RotationChartVO> rcList = new ArrayList<>();
            for (int i = 0; i < img.length; i++) {
                if (i < 4) {
                    // 上传图片并替换图片背景
                    Grip grip = new Grip();
                    int type = 0;
                    try {
                        InputStream is = new URL(img[i]).openStream();
                        BufferedImage sourceImg = ImageIO.read(is);
                        int width = sourceImg.getWidth();
//                        int height = sourceImg.getHeight();
                        if (width == 500) {
                            type = 1;
                        } else if (width == 2947) {
                            type = 2;
                        }else if(width == 1000){
                            type = 3;
                        }else if(width == 591){
                            type =4;
                        }else if(width == 1500){
                            type =5;
                        }else if(width == 400){
                            type =6;
                        }
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                    File fileByUrl = grip.getFileByUrl(img[i], "jpg");
                    String imgUrl = null;
                    try {
                        String fileUrl = this.getClass().getClassLoader().getResource("static/default.png").getPath();
                        fileUrl = URLDecoder.decode(fileUrl, "utf-8");
                        log.info("获取模板地址路径：" + fileUrl);
                        imgUrl = shoppingMainImage + grip.createNewPic(fileByUrl, fileUrl, "", type);
                    } catch (IOException e) {
                        e.printStackTrace();
                        return null;
                    }


//                    String imgUrl = shoppingMainImage + TaoBaoUtils.uploadFile(img[i], "", "upload/store/" + "33307/" + DateHelper.getDate());
                    RotationChartVO chartVO = new RotationChartVO();
                    if (i == 0) {
                        vo.setPhotoId(0L);
                        vo.setImg(imgUrl);
                        chartVO.setId(0L);
                        chartVO.setUrl(imgUrl);
                    } else {
                        chartVO.setId(0L);
                        chartVO.setUrl(imgUrl);
                    }
                    rcList.add(chartVO);
                }
            }
            vo.setRotationChart(rcList);
            // 组装规格json
        }
        List<GoodsInventoryDetailsToJsons> inventoryDetails = new ArrayList<>();
        if (!StringUtils.isEmpty(dto.getUnit())) {
            // 查询出规格属性名id
            List<Integer> specId = shoppingGoodsMapper.selectGoodsSpecification(dto.getUnit());

            // 规格
            String[] specifications = dto.getSizeList().split(",");
            if (specId.size() <= 0) {
                // 则去新建这个属性
                SpecPropertyDTO spd = new SpecPropertyDTO();
                spd.setName(dto.getUnit());
                shoppingGoodsMapper.insertSpecIfication(spd);
                specId.add(spd.getId());
            }
//            if (specId.size() > 0) {
                for (int i = 0; i < specifications.length; i++) {
                    GoodsInventoryDetailsToJsons gid = new GoodsInventoryDetailsToJsons();
                    // 查询这个规格是否已经存在数据库
                    List<Integer> count = shoppingGoodsMapper.selectSpecPropertyByNameOrId(specifications[i], specId.get(0));
                    int propertyId = 0;
                    if (count.size() > 0) {
                        // 已存在
                        propertyId = count.get(0);
                    } else {
                        // 则不存在 需要新增
                        SpecPropertyDTO specPropertyDTO = new SpecPropertyDTO();
                        specPropertyDTO.setName(specifications[i]);
                        specPropertyDTO.setSpecId(specId.get(0));
                        goodsSpecMapper.insertProperty(specPropertyDTO);
                        propertyId = specPropertyDTO.getId();
                    }
                    gid.setId(propertyId + "_");
                    gid.setIntegral(0);
                    gid.setGiveIntegral(0);
                    gid.setCount(0);
                    gid.setVipPrice(BigDecimal.valueOf(Long.valueOf(dto.getPrice())).divide(new BigDecimal(100)).toString());
                    gid.setPrice(BigDecimal.valueOf(Long.valueOf(dto.getAuthPrice())).divide(new BigDecimal(100)).toString());
                    gid.setGoodsCostingPrice("0");
                    gid.setShowCostingPrice("0");
                    gid.setBuyerPrice("0");
                    gid.setPriceType("2");
                    gid.setImgPath(vo.getImg());
                    inventoryDetails.add(gid);
                }
//            }
        }
        vo.setGoodsInventoryDetail(JSON.toJSONString(inventoryDetails));
        vo.setGoodsName(dto.getTitle());
        vo.setGoodsSerial(dto.getArticleNumber());
        vo.setGoodsDetails(dto.getImageAndText().substring(0, dto.getImageAndText().length() - 2));
        vo.setGoodsDetails(vo.getGoodsDetails().replace("https://du.hupucdn.com/news_byte52287byte_5b6f8390e75ad455639e5f376665fcd7_w1125h231.png?imageView2/2/w/960", "https://image.yilianbaihui.cn/consumer/upload/after.png"));
        vo.setGoodsDetails(vo.getGoodsDetails().replace("https://du.hupucdn.com/FlyWbf5CVPLRropEWYbVH12kUGWs?imageView2/2/w/960", "https://image.yilianbaihui.cn/consumer/upload/security.jpg"));
        vo.setGoodsPrice(BigDecimal.valueOf(Long.valueOf(dto.getAuthPrice())).divide(new BigDecimal(100)));
        vo.setVipPrice(BigDecimal.valueOf(Long.valueOf(dto.getPrice())).divide(new BigDecimal(100)));
        return vo;
    }

    /**
     * 上传商品详情图片
     * @param goodsDTO
     * @return
     */
    @Override
    public String uploadGoodsDetails(GoodsDTO goodsDTO) {
        // 过滤图片
        if (!StringUtils.isEmpty(goodsDTO.getGoodsDetails())) {
            Document parse = Jsoup.parse(goodsDTO.getGoodsDetails());
            Elements imgs = parse.getElementsByTag("img");
            for (Element img :imgs) {
                String src = img.attr("src");
                if (!src.contains("image.yilianbaihui.cn")){
                    String url = TaoBaoUtils.uploadFileGoods(src, "", "upload/store/33307");
                    if(StringUtils.isBlank(url)){
                        img.remove();
                    }else {
                        img.attr("src", shoppingMainImage + url);
                    }
                }
            }
            return parse.body().children().toString();
        }
        return null;
    }

    /**
     * 修改商品展示详情
     * @param dto
     */
    @Override
    public void updateGoodsDetailsBySku(GoodsDTO dto) {
        shoppingGoodsMapper.updateGoodsDetailsBySku(dto);
    }

    /**
     * 获取特定时间内的商品
     * @return
     */
    @Override
    public List<GoodsDTO> queryGoodsByTime() {
        return shoppingGoodsMapper.selectGoodsByTime();
    }

    /**
     * 上传商品验证型号是否已存在
     * @param goodsSerial
     * @return
     */
    @Override
    public int verificationGoodsSerial(String goodsSerial) {
        return shoppingGoodsMapper.selectVerificationGoodsSerial(goodsSerial);
    }

    /**
     * 修改商品的规格重量
     * @param id
     * @param goodsInventoryDetail
     */
    @Override
    public void modifyGoodsWeight(Integer id, String goodsInventoryDetail) {
        shoppingGoodsMapper.updateGoodsWeight(id, goodsInventoryDetail);
    }
}
